import scala.actors.Actor

class TeamLeader extends Actor {
  val random = new scala.util.Random;
  var arrivedCustomers = 0;
  var arrivedProgrammers = 0;
  var waitingList: List[Any] = Nil;
  var secretary: Secretary = null.asInstanceOf[Secretary];

  def act() {
    loop {
      receive {
        case notifyTeamLeader(list: List[Any]) =>
          secretary = sender.asInstanceOf[Secretary];

          println(" > TeamLeader > Verstuur uitnodiging voor overleg.");
          list.foreach(i => inviteToMeeting(i))
          waitingList = list;

          println(" > TeamLeader > Wacht totdat iedereen is aangekomen.");

        case `arrived` =>
          if (sender.isInstanceOf[Customer]) {
            arrivedCustomers += 1;
          } else if (sender.isInstanceOf[Programmer]) {
            arrivedProgrammers += 1;
          }

          if (arrivedCustomers == 3 || arrivedProgrammers == 2) {
            println(" > TeamLeader > Iedereen is aangekomen.");
            Thread.sleep(1000);

            println(" > TeamLeader > Overleg is begonnen.");
            Thread.sleep(random.nextInt(1000)); // Simuleer wachttijd
            waitingList.foreach(i => endOfMeeting(i));

            secretary ! teamLeaderIsFree; // Laat secetaresse weten dat hij weer vrij is.
            arrivedCustomers = 0;
            arrivedProgrammers = 0;
          }
      }
    }
  }

  private def inviteToMeeting(obj: Any) {
    if (obj.isInstanceOf[Customer]) {
      obj.asInstanceOf[Customer] ! sentInvite;
    } else if (obj.isInstanceOf[Programmer]) {
      obj.asInstanceOf[Programmer] ! sentInvite
    }
  }

  private def endOfMeeting(obj: Any) {
    if (obj.isInstanceOf[Customer]) {
      obj.asInstanceOf[Customer] ! notifyEndOfMeeting;
    } else if (obj.isInstanceOf[Programmer]) {
      obj.asInstanceOf[Programmer] ! notifyEndOfMeeting
    }
  }
}

case object TeamLeader extends Message